﻿@using si.caha.Model;
@using si.caha.Repository;
@using System.Collections.Generic;
@using System.Web.Script.Serialization;

@{
    if(IsPost)
    {
        var dataContext = new DataContext();
        var itemRepository = new ItemRepository(dataContext);
        var item = new Item();
        var response = new Dictionary<string, string>();
        
        item.ItemId = Request["itemId"].AsInt();
        // if itemId already exists, we're in edit mode
        bool edit = item.ItemId > 0;
        
        item.Title = Request["title"];
        item.Description = Request["description"];
        
        var price = -1.0;
        bool priceParseSuccesful = Double.TryParse(Request["price"], out price);
        item.Price = price;
        
        var categoryId = Request["category"].AsInt();
        
        if (categoryId > 0)
        {
            item.CategoryId = categoryId;
        }
        
        response = itemRepository.Save(item); // after save, new PK is already here > sweet!
        
        if (!priceParseSuccesful)
        {
            response.Add("Price", "Price is not in valid number format!");
        }
        
        if (response.Count == 0)
        {
            response.Add("ItemId", item.ItemId.ToString());
            if (edit) 
            {
                response.Add("Message", "Item saved");
            }
            else
            {
                response.Add("Message", "Item created");
            }
        }
        
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string json = serializer.Serialize((object)response);
        
        Response.Write(json);
    }
    else
    {
        Response.Redirect("~/Admin");
    }
}
